'use strict';

const bcrypt = require('bcryptjs');
const { Service } = require('egg');
const { Op } = require('sequelize');

class CourseService extends Service {
  /**
   * 根据分页和搜索条件获取课程
   * @param {Object} where 查询用户的条件
   * @param {Number} page 当前分页
   * @param {Number} pageSize 当前页每页多少条

   */
  async getPage(where, page, pageSize) {
    const { Course } = this.ctx.model;
    try {
        const res = Course.findAndCountAll({
            where: {
                ...where
            },
            order:[
                // id 降序
                ['created_at','DESC']
            ],
            offset: pageSize * (page - 1),
            limit: pageSize,
        });
        return res
    } catch (e) {
        throw new Error(e);
    }
  }

  /**
   * 注册用户数据
   * @param {Object} data
   */
  async createItem(data) {
    const { Course } = this.ctx.model;
    const userExists = await Course.findOne({
      attributes: ['id'],
      where: {
        [Op.or]: {
          course_name: data.course_name,
        },
      },
    });
    if (userExists) throw new Error('该课程已经存在');
    const newUser = await Course.create(data);
    return newUser.dataValues;
  }

  /**
   * 根据id删除对应的用户
   * @param {Number} uid
   */
  async deleteItemById(id) {
    return await this.ctx.model.Course.destroy({ where: { id } });
  }

  /**
   * 根据ID修改用户信息
   * @param {Number} id 用户ID
   * @param {Object} data 要修改的用户信息
   */
  async updateItemById(id, data) {
    const { Course } = this.ctx.model;
    const { course_name } = data;
    const andWhere = { id: { [Op.ne]: id } };
    let neenCheck = false;
   if (course_name) {
      neenCheck = true;
      andWhere.course_name = course_name;
    }

    if (neenCheck) {
      const userExists = await Course.findOne({
        attributes: ['id'],
        where: { [Op.and]: andWhere },
      });
      if (userExists) throw new Error('该账号已经存在');
    }

    return await Course.update(data, { where: { id } });
  }
  // 所有列表
  async allList(where) {
    const { Course } = this.ctx.model;
    return Course.findAll({
      where
    });
  }
}

module.exports = CourseService;
